<template>
  <div class="highLevelVideo-page">
    <breadcrumb />
    <div class="search-container">
      <Search @search="getSearchParams" />
    </div>
    <div class="table-container">
      <div class="table-component">
        <div class="submit-btns">
          <div></div>
          <div class="submit-btns-right">
            <el-button
              type="primary"
              class="submit-btn-status"
              @click="statusData"
            >
              <img class="icon-img" :src="iconStatus" alt="" />
              修改使用状态</el-button
            >
            <el-button type="primary" class="submit-btn-add" @click="addData">
              <img class="icon-img" :src="iconAdd" alt="" />
              新增</el-button
            >
            <el-button
              type="primary"
              class="submit-btn-import"
              @click="importData"
            >
              <img class="icon-img" :src="iconImport" alt="" />导入</el-button
            >
            <el-button
              type="primary"
              class="submit-btn-export"
              @click="exportData"
            >
              <img class="icon-img" :src="iconExport" alt="" />导出</el-button
            >
          </div>
        </div>
        <div class="table">
          <el-table
            :data="table.data"
            :loading="table.loading"
            @selection-change="handleSelectionChange"
            style="width: 100%"
            :header-cell-style="{
              background: '#F1F1F1',
              'font-size': '14px',
              'font-weight': 600,
              color: '#333333',
            }"
            :cell-style="{
              'font-size': '14px',
              'font-weight': 400,
              color: '#333333',
            }"
          >
            <el-table-column type="selection" width="55" fixed="left" />
            <el-table-column label="序号" min-width="60" fixed="left">
              <template #default="scope">
                {{ (scope.$index + 1).toString().padStart(2, "0") }}
              </template>
            </el-table-column>
            <el-table-column prop="code" label="设备编号" min-width="220" />
            <el-table-column prop="vendor" label="设备厂家" min-width="120" />
            <el-table-column prop="state" label="使用状态" min-width="80">
              <template #default="scope">
                <div v-if="scope.row.state == 1" class="inUse">使用中</div>
                <div v-else-if="scope.row.state == 2" class="NotProduction">
                  未投产
                </div>
                <div v-else-if="scope.row.state == 3" class="underRepair">
                  维修中
                </div>
                <div v-else class="scrapped">已报废</div>
              </template>
            </el-table-column>

            <el-table-column prop="status" label="在线状态" min-width="80">
              <template #default="scope">
                <div v-if="scope.row.status === null">-</div>
                <div v-else>{{ scope.row.status }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="heartbeatTime"
              label="最后心跳时间"
              min-width="120"
            >
              <template #default="scope">
                <div v-if="scope.row.heartbeatTime === null">-</div>
                <div v-else>{{ scope.row.heartbeatTime }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="ip" label="设备ip" min-width="100" />

            <el-table-column label="操作" width="110" fixed="right">
              <template #default="scope">
                <el-button
                  @click="editData(scope.row)"
                  type="primary"
                  size="small"
                  link
                  style="color: #007aff; font-size: 14px"
                  >编辑</el-button
                >
                <el-button
                  @click="deleteData(scope.row)"
                  type="primary"
                  size="small"
                  link
                  style="color: #007aff; font-size: 14px"
                  >删除</el-button
                >
              </template>
            </el-table-column>
            <template #empty>
              <el-empty :image="imgNone" />
            </template>
          </el-table>
        </div>
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="pagination.pageSizes"
            layout="total,sizes, prev, pager, next, jumper"
            :total="table.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <el-dialog
          v-model="dialogVisible"
          :title="title"
          destroy-on-close
          :before-close="handleClose"
          :close-on-click-modal="false"
          :width="
            componentTag === statusComponent
              ? '520px'
              : componentTag === importComponent
              ? '800px'
              : '1000px'
          "
        >
          <template #header>
            <div
              v-if="
                componentTag === addComponent || componentTag === editComponent
              "
              class="row"
            >
              <div>{{ title }}</div>
              <el-tooltip
                content="仅当设备处于使用中，可进行泊位关联"
                placement="right"
              >
                <img class="icon-tips" :src="tips" alt="" />
              </el-tooltip>
            </div>
          </template>
          <component
            :is="componentTag"
            @operationDone="operationDone"
            :operationId="operationId"
          >
          </component>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup>
import breadcrumb from "@/components/breadcrumb/index.vue";
import Search from "./components/search.vue";
import iconStatus from "@/assets/image/btn/icon-status.png";
import iconAdd from "@/assets/image/btn/icon-add.png";
import iconImport from "@/assets/image/btn/icon-import.png";
import iconExport from "@/assets/image/btn/icon-export.png";
import tips from "@/assets/image/tips2.png";
import statusComponent from "./components/statusComponent.vue";
import addComponent from "./components/addComponent.vue";
import editComponent from "./components/editComponent.vue";
import importComponent from "./components/importComponent.vue";
import { ref, reactive, shallowRef } from "vue";
import {
  getVideoList,
  getDeleteVideo,
  getExportVideoPile,
} from "./request.js";
const imgNone = new URL("@/assets/image/imgNone.png", import.meta.url).href;
const searchModel = ref({
  code: "",
  vendor: "",
  state: 1,
  status: "",
});

const getSearchParams = (value) => {
  searchModel.value = value;
  // console.log(value);
  getData();
};

// 弹窗
const title = ref("");
const dialogVisible = ref(false);
const componentTag = shallowRef("");
const operationId = ref("");
const operationDone = (r) => {
  dialogVisible.value = false;
  operationId.value = "";
  if (!r) {
    getData();
  }
};

// 修改使用状态
const statusData = () => {
  if (bingList.value.length === 0) {
    ElMessage.error("请选择设备信息");
    return;
  }
  title.value = "修改使用状态";
  operationId.value = bingList.value;
  componentTag.value = statusComponent;
  dialogVisible.value = true;
};

// 新增按钮
const addData = () => {
  title.value = "新增视频桩信息";
  componentTag.value = addComponent;
  dialogVisible.value = true;
};

// 编辑按钮
const editData = (row) => {
  title.value = "编辑视频桩信息";
  operationId.value = row;
  componentTag.value = editComponent;
  dialogVisible.value = true;
};

// 导入
const importData = () => {
  title.value = "导入视频桩信息";
  componentTag.value = importComponent;
  dialogVisible.value = true;
};

// 删除按钮
const deleteData = (row) => {
  ElMessageBox.confirm(`您确定要删除视频桩[${row.code}]吗？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await getDeleteVideo(row.id).then((res) => {
      console.log("res ===>", res);
      if (res.data.code === 0) {
        getData();
        ElMessage({
          type: "success",
          message: `已删除视频桩[${row.code}]`,
        });
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  });
};

// 导出按钮
const exportData = () => {
  ElMessageBox.confirm(`您确认要导出数据？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await getExportVideoPile({
      code: searchModel.value.code,
      vendor: searchModel.value.vendor,
      state: searchModel.value.state,
      status: searchModel.value.status,
      category: 2,
    })
      .then((res) => {
        const fileName = extractFileNameFromHeaders(res.headers);
        const url = window.URL.createObjectURL(new Blob([res.data]));
        const link = document.createElement("a");
        link.href = url;
        link.download = fileName;
        link.click();
      })
      .catch((err) => {
        console.log("err ===>", err);
      });
  });
};

function extractFileNameFromHeaders(headers) {
  const contentDisposition = headers.get("content-disposition") || "";

  const matches = contentDisposition.match(/filename\*=\s*utf-8''([^;]+)/);

  if (matches != null && matches[1]) {
    return decodeURIComponent(matches[1].replace('"', ""));
  }
  return "unknown-file.pdf"; // 默认文件名
}

// 表格
const table = reactive({
  data: [{}],
  total: 0,
  loading: true,
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 30, 50],
});

const handleCurrentChange = (value) => {
  pagination.currentPage = value;
  getData();
};

const handleSizeChange = (value) => {
  pagination.pageSize = value;
  getData();
};

const getData = async () => {
  console.log(searchModel.value);
  await getVideoList({
    code: searchModel.value.code,
    vendor: searchModel.value.vendor,
    state: searchModel.value.state,
    status: searchModel.value.status,
    category: 2,
    pageNo: pagination.currentPage,
    pageSize: pagination.pageSize,
  }).then((res) => {
    if (res.data.code === 0) {
      table.data = res.data.result.items;
      table.total = parseInt(res.data.result.total);
      table.loading = false;
    }
  });
};

getData();

const bingList = ref([]);

const handleSelectionChange = (val) => {
  bingList.value = val.map((proxy) => proxy.id);
  console.log("bingList ===>", bingList.value);
};
</script>

<style lang="less" scoped>
.highLevelVideo-page {
  .search-container {
    margin-top: 16px;
    min-height: 100%;
    padding: 24px 24px 8px 24px;
    background: #fff;
    border-radius: 6px;
  }
  .table-container {
    margin-top: 16px;
    min-height: 100%;
    padding: 24px;
    background: #fff;
    border-radius: 6px;
  }
  .table-component {
    .submit-btns {
      display: flex;
      justify-content: space-between;
      margin-bottom: 24px;
    }
    .submit-btns-right {
      display: flex;
    }
    .submit-btn-status {
      background: #ff9623;
      border: 1px solid #ff9623;
      border-radius: 2px;
      margin-left: 87px;
      padding: 5px 16px;
    }
    .submit-btn-add {
      background: #007aff;
      border: 1px solid #007aff;
      border-radius: 2px;
      margin-left: 12px;
      padding: 5px 16px;
    }
    .submit-btn-import {
      background: #00d1ff;
      border: 1px solid #00d1ff;
      border-radius: 2px;
      margin-left: 12px;
      padding: 5px 16px;
    }
    .submit-btn-export {
      background: #35c362;
      border: 1px solid #35c362;
      border-radius: 2px;
      margin-left: 12px;
      padding: 5px 16px;
    }
    .icon-img {
      width: 16px;
      height: 16px;
      margin-right: 8px;
    }
    .table {
      margin-bottom: 15px;
      .inUse {
        border: 1px solid #35c362;
        border-radius: 2px;
        font-weight: 400;
        font-size: 14px;
        color: #35c362;
        text-align: center;
        width: 52px;
        height: 20px;
        line-height: 18px;
      }
      .NotProduction {
        border: 1px solid #007aff;
        border-radius: 2px;
        font-weight: 400;
        font-size: 14px;
        color: #007aff;
        text-align: center;
        width: 52px;
        height: 20px;
        line-height: 18px;
      }
      .underRepair {
        border: 1px solid #f18532;
        border-radius: 2px;
        font-weight: 400;
        font-size: 14px;
        color: #f18532;
        text-align: center;
        width: 52px;
        height: 20px;
        line-height: 18px;
      }
      .scrapped {
        border: 1px solid #de2910;
        border-radius: 2px;
        font-weight: 400;
        font-size: 14px;
        color: #de2910;
        text-align: center;
        width: 52px;
        height: 20px;
        line-height: 18px;
      }
    }
    .pagination {
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
  .icon-tips {
    width: 20px;
    height: 20px;
  }
  .row {
    display: flex;
    align-items: center;
  }
}
</style>